package com.ruoyi.system.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TemporaryStaffAccount;
import com.ruoyi.system.domain.ViewConfigPushMes;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TemporaryStaffAccountMapper;
import com.ruoyi.system.mapper.ViewConfigPushMesMapper;
import com.ruoyi.system.service.SysRemindService;
import com.ruoyi.system.service.TemporaryStaffAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 临时施工人员台账(TemporaryStaffAccount)表服务实现类
 *
 * @author makejava
 * @since 2022-11-18 09:36:47
 */
@Service
public class TemporaryStaffAccountServiceImpl implements TemporaryStaffAccountService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TemporaryStaffAccountMapper temporaryStaffAccountMapper;
    @Autowired
    private SysRemindService sysRemindService;
    @Resource
    private ViewConfigPushMesMapper viewConfigPushMesMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccount queryById(Integer id) {
        return this.temporaryStaffAccountMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param temporaryStaffAccount 筛选条件
     * @param pageRequest           分页对象
     * @return 查询结果
     */
    @Override
    public Page<TemporaryStaffAccount> queryByPage(TemporaryStaffAccount temporaryStaffAccount, PageRequest pageRequest) {
        long total = this.temporaryStaffAccountMapper.count(temporaryStaffAccount);
        return new PageImpl<>(this.temporaryStaffAccountMapper.queryAllByLimit(temporaryStaffAccount, pageRequest), pageRequest, total);
    }

    @Override
    public TemporaryStaffAccount selectByName(String name) {
        TemporaryStaffAccount temporaryStaffAccount = new TemporaryStaffAccount();
        temporaryStaffAccount.setName(name);
        temporaryStaffAccount.setYn(1);
        List<TemporaryStaffAccount> list = selectList(temporaryStaffAccount);
        return StringUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public List<TemporaryStaffAccount> selectList(TemporaryStaffAccount temporaryStaffAccount) {
        List<TemporaryStaffAccount> temporaryStaffAccounts = temporaryStaffAccountMapper.queryAll(temporaryStaffAccount);
        if (null != temporaryStaffAccount
                && null != temporaryStaffAccount.getQueryFlag()
                && temporaryStaffAccount.getQueryFlag().equals(2)) {
            List<TemporaryStaffAccount> temporaryStaffAccountList = new ArrayList<>();
            for (TemporaryStaffAccount var : temporaryStaffAccounts) {
                //已经离开
                if (StringUtils.isNotEmpty(var.getOutFactoryTime())) {
                    continue;
                }

                //计划离场大于今天
                String remind = var.getPlanOutFactoryTime();
                Date date = new Date();
                boolean after = date.after(DateUtils.parseDate(remind));
                if (after) {
                    continue;
                }
                temporaryStaffAccountList.add(var);
            }
            return temporaryStaffAccountList;
        }
        return temporaryStaffAccounts;
    }

    /**
     * 新增数据
     *
     * @param temporaryStaffAccount 实例对象
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccount insert(TemporaryStaffAccount temporaryStaffAccount) {
        TemporaryStaffAccount temporaryStaffAccountQuery = new TemporaryStaffAccount();
        temporaryStaffAccountQuery.setCardNumber(temporaryStaffAccount.getCardNumber());
        List<TemporaryStaffAccount> temporaryStaffAccounts = temporaryStaffAccountMapper.queryAll(temporaryStaffAccountQuery);
        if (!CollectionUtils.isEmpty(temporaryStaffAccounts)) {
            String substring = temporaryStaffAccount.getCardNumber().substring(temporaryStaffAccount.getCardNumber().length() - 4);
            temporaryStaffAccount.setName(temporaryStaffAccount.getName() + substring);
        }

        int insert = this.temporaryStaffAccountMapper.insert(temporaryStaffAccount);
        if (insert > 0) {
            SysUser sysUser = new SysUser();
            sysUser.setVid(temporaryStaffAccount.getId());
            String pinyin = PinyinUtil.getPinyin(temporaryStaffAccount.getName(), "");
            sysUser.setNickName(temporaryStaffAccount.getName());
            sysUser.setUserName(pinyin);
            sysUser.setPassword(SecurityUtils.encryptPassword("Sdkmqzq@2023"));
            sysUser.setStatus("0");
            sysUser.setDelFlag("0");
            sysUser.setCreateBy("sys");
            sysUser.setCreateTime(new Date());
            sysUser.setRemark("临时施工人员");
            sysUser.setFirstLogin("0");
            sysUser.setCardNumber(temporaryStaffAccount.getCertificateNumber());
            sysUserMapper.insertUser(sysUser);
        }

        return temporaryStaffAccount;
    }

    /**
     * 修改数据
     *
     * @param temporaryStaffAccount 实例对象
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccount update(TemporaryStaffAccount temporaryStaffAccount) {
        temporaryStaffAccount.setModifyBy("admin");
        temporaryStaffAccount.setModifyDate(new Date());
        this.temporaryStaffAccountMapper.update(temporaryStaffAccount);
        return this.queryById(temporaryStaffAccount.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.temporaryStaffAccountMapper.deleteById(id) > 0;
    }


    @Override
    public String importExcel(List<TemporaryStaffAccount> temporaryStaffAccounts, boolean updateSupport, String operName) {
        if (StringUtils.isNull(temporaryStaffAccounts) || temporaryStaffAccounts.isEmpty()) {
            throw new ServiceException("导入用户数据不能为空！");
        }

        List<TemporaryStaffAccount> saveList = new ArrayList<>();

        List<TemporaryStaffAccount> temporaryStaffAccountList = temporaryStaffAccountMapper.queryAll(new TemporaryStaffAccount());

        Map<String, TemporaryStaffAccount> initMap = temporaryStaffAccountList.stream()
                .collect(Collectors.toMap(TemporaryStaffAccount::getCardNumber, el -> el, (e1, e2) -> e1));

        for (TemporaryStaffAccount var : temporaryStaffAccounts) {
            if (initMap.containsKey(var.getCardNumber())) {
                continue;
            }
            saveList.add(var);
        }

        if (CollectionUtils.isEmpty(saveList)) {
            return "无数据导入";
        }

        temporaryStaffAccountMapper.insertBatch(saveList);
        return "成功";
    }

    @Scheduled(cron = "0 0 6 * * ?")
    public void checkPermitReportFile() {
        TemporaryStaffAccount temporaryStaffAccount = new TemporaryStaffAccount();
        List<TemporaryStaffAccount> relateds = temporaryStaffAccountMapper.queryAll(temporaryStaffAccount);
        if (CollectionUtils.isEmpty(relateds)) {
            return;
        }

        relateds.forEach(var -> {
            String remind = var.getPlanOutFactoryTime();
            Date date = new Date();
            boolean after = date.after(DateUtils.parseDate(remind));
            if (after) {
                String stringBuffer =
                        "姓名:" + var.getName() +
                                "即将到期。";

                ViewConfigPushMes viewConfigPushMes = new ViewConfigPushMes();
                viewConfigPushMes.setViewName("临时施工人员信息");
                List<ViewConfigPushMes> configPushMes = viewConfigPushMesMapper.queryByViewKey(viewConfigPushMes);
                if (!CollectionUtils.isEmpty(configPushMes)) {
                    ViewConfigPushMes pushMes = configPushMes.stream().findFirst().orElse(new ViewConfigPushMes());
                    if (com.ruoyi.common.utils.StringUtils.isNotEmpty(pushMes.getViewValue())) {
                        boolean contains = pushMes.getViewValue().contains(",");
                        if (contains) {
                            String[] split = pushMes.getViewValue().split(",");
                            for (String vars : split) {
                                sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, Integer.valueOf(vars));
                            }
                        } else {
                            sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, Integer.valueOf(pushMes.getViewValue()));
                        }
                    }
                }
            }
        });
    }

}
